package com.zspringboot.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zspringboot.demo.entity.Menu;
import com.zspringboot.demo.entity.Role;
import com.zspringboot.demo.entity.RoleMenu;
import com.zspringboot.demo.mapper.RoleMapper;
import com.zspringboot.demo.mapper.RoleMenuMapper;
import com.zspringboot.demo.service.IMenuService;
import com.zspringboot.demo.service.IRoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laolang
 * @since 2024-02-25
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private IMenuService menuService;
    @Override
    public void setRoleMenu(Integer roleId, List<Integer> menuIds) {
//        QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
        RoleMenu roleMenu;
        // 先删除当前角色id所有的绑定关系
        roleMenuMapper.deleteRoleId(roleId);
//        roleMenuMapper.selectById(roleId);
//            roleMenuMapper.deleteById(roleMenu);
        // 将前端传过来的菜单id数组绑定到当前这个角色的id上去
        int k=0;
        for (Integer menuId:menuIds){
            Menu menu = menuService.getById(menuId);
            if ((k==0)&&menu.getPid()!=null && !menuIds.contains(menu.getPid())){
                // 二级菜单不等于空 且 传过来的 MenuID数组里面没有他的父级id
                // 那么我们补上父级id
                roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(menu.getPid());
                roleMenuMapper.insert(roleMenu);
                k++;
            }
            roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenuMapper.insert(roleMenu);
        }

    }

    @Override
    public List<Integer> getRoleMenu(Integer roleId) {
        return roleMenuMapper.selectByRoleId(roleId);
    }
}
